package sessions;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *.
 * @author momsse
 */
public abstract class AbstractFacade<T> {

    private Class<T> entityClass;

    /**
     * Constructor.
     * @param entityClass : the entity class
     */
    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    /**
     * Get the EntityManager.
     * @return the EntityManager
     */
    protected abstract EntityManager getEntityManager();

    /**
     * Insert an entity in base.
     * @param entity : the entity to insert
     * @return the managed entity
     */
    public T create(T entity) {
        getEntityManager().persist(entity);
        return entity;
    }

    /**
     * Update an entity in base.
     * @param entity : the entity to update
     */
    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    /**
     * Remove an entity from the base.
     * @param entity the entity to remove
     */
    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    /**
     * Find an entity by his id.
     * @param id : the entity's id
     * @return the entity
     */
    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    /**
     * Find all entities from the base.
     * @return entities
     */
    public List<T> findAll() {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    /**
     * Find entities in range.
     * @param range : the range
     * @return entities
     */
    public List<T> findRange(int[] range) {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    /**
     * Count entties in the base.
     * @return the number of entities
     */
    public int count() {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
}
